#!/usr/bin/env python

import os
import sys
import document
import wordlist
import pretty

class Application():
	def __init__(self):
		self.cmds=[]	
		self.quit = False
		self.add_command("q", self.doQuit)
		self._register()

	def add_command(self, cmd_str, caller):
		self.cmds.append([cmd_str, caller])

	def _execute(self, cmd, *args):
		matched = filter(lambda x: x[0] == cmd, self.cmds)
			
		if len(matched) == 0:
			print "warning: unsupported command : %s" % cmd
		else:
			matched[0][1](*args)
	
	def _register(self):
		pass

	def run(self):
		self.quit = False
		while(not self.quit):
			c = raw_input(">> ")
			cmds = c.split()
			if len(cmds) > 0:
				cmd_str = c.split()[0]
				args = c.split()[1:]
			
				self._execute(cmd_str, *args)

	def doQuit(self, *args):
		self.quit = True

class WordStudy(Application):
	def __init__(self, fn):
		Application.__init__(self)
		self.doc = document.Document(fn)
		self.dictionary = wordlist.Dictionary()
		self._build_database()

	def _register(self):
		self.add_command("w", self.on_word)
		self.add_command("wf", self.on_wordf)
		self.add_command("f", self.on_sentence)

	# generate self.db, self.dbf in dict from the given document
	# self.db is based on word, self.dbf is based on the family word
	# key is word, value is the list of sentence id
	def _build_database(self):
		self.db = {}
		sentences = self.doc.sentences
		for i in range(len(sentences)):
			s = sentences[i].replace(',', ' ').strip()
			words = map(lambda x: x.strip().lower(), s.split())

			for word in words:
				if not self.dictionary.has(word):
					continue

				if word in self.db:
					if self.db[word][-1] != i:
						self.db[word] = self.db[word] + [i]
				else:
					self.db[word] = [i]

		self.dbf = {}
		for w, sids in self.db.iteritems():
			fw = self.dictionary.get_family(w) 		
			if fw in self.dbf:
				self.dbf[fw] += self.db[w]
				self.dbf[fw] = list(set(self.dbf[fw]))
			else:
				self.dbf[fw] = self.db[w]

	# generate self.count in list
	# 
	def _compute_count(self):
		self.count = []
		for key, value in self.db.iteritems():
			self.count.append([key, len(value)])

		self.count.sort(key=lambda x: x[1], reverse=True)
		save(self.fn_base+"wc", map(lambda x: x[0]+","+str(x[1]), self.count))

	def on_word(self, *args):
		count = []
		count = map(lambda x: [x[0], len(x[1])], self.db.iteritems())
		count = sorted(count, key=lambda x: x[1], reverse=True)
		
		for c in count:
			print c[0], c[1]

	def on_wordf(self, *args):
		count = []
		count = map(lambda x: [x[0], len(x[1])], self.dbf.iteritems())
		count = sorted(count, key=lambda x: x[1], reverse=True)
		
		for c in count:
			print c[0], c[1]

	def on_sentence(self, *args):
		if len(args) == 0:
			print "help : s <word>"	
			return

		w = args[0]
		try:
			wf = self.dictionary.get_family(w)
			#print wf	
			sids = self.dbf[wf]
			#print sids
			#print self.dictionary.get_members(wf)
			for sid in sids:
				pretty.print_sentence(self.doc.sentences[sid], self.dictionary.get_members(wf))
				print

		except KeyError: 
			print "Not found"
		
if __name__=="__main__":
	fn = sys.argv[1]
	app = WordStudy(fn)
	app.run()
		


